import { Response } from 'express';
import { ErrorLogService } from '../services/errorLogService';
import { AuthorizationError } from '../types/errors';
import { ErrorSeverity } from '../types/audit';
import { isAdmin } from '../middleware/authorization';
import { AuthenticatedRequest } from '../types/auth';

/**
 * 错误日志控制器
 */
export class ErrorLogController {
  /**
   * 搜索错误日志
   */
  static async searchLogs(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      if (!isAdmin(req)) {
        throw new AuthorizationError('需要管理员权限');
      }

      const params = {
        startDate: req.query.startDate ? new Date(req.query.startDate as string) : undefined,
        endDate: req.query.endDate ? new Date(req.query.endDate as string) : undefined,
        level: req.query.level as 'ERROR' | 'WARN' | 'INFO' | undefined,
        code: req.query.code as string,
        severity: req.query.severity as ErrorSeverity,
        userId: req.query.userId as string,
        page: parseInt(req.query.page as string) || 1,
        limit: parseInt(req.query.limit as string) || 20
      };

      const result = await ErrorLogService.searchLogs(params);

      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      if (error instanceof AuthorizationError) {
        res.status(403).json({
          success: false,
          error: {
            code: 'FORBIDDEN',
            message: error.message
          }
        });
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'INTERNAL_ERROR',
          message: '获取错误日志失败'
        }
      });
    }
  }

  /**
   * 获取统计信息
   */
  static async getStats(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      if (!isAdmin(req)) {
        throw new AuthorizationError('需要管理员权限');
      }

      const startDate = req.query.startDate ? new Date(req.query.startDate as string) : undefined;
      const endDate = req.query.endDate ? new Date(req.query.endDate as string) : undefined;

      const stats = await ErrorLogService.getStats(startDate, endDate);

      res.json({
        success: true,
        data: stats
      });
    } catch (error) {
      if (error instanceof AuthorizationError) {
        res.status(403).json({
          success: false,
          error: {
            code: 'FORBIDDEN',
            message: error.message
          }
        });
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'INTERNAL_ERROR',
          message: '获取统计信息失败'
        }
      });
    }
  }

  /**
   * 清理过期日志
   */
  static async cleanupLogs(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      if (!isAdmin(req)) {
        throw new AuthorizationError('需要管理员权限');
      }

      const daysToKeep = parseInt(req.query.daysToKeep as string) || 30;
      const deletedCount = await ErrorLogService.cleanupOldLogs(daysToKeep);

      res.json({
        success: true,
        data: {
          deletedCount,
          message: `成功删除 ${deletedCount} 条过期错误日志`
        }
      });
    } catch (error) {
      if (error instanceof AuthorizationError) {
        res.status(403).json({
          success: false,
          error: {
            code: 'FORBIDDEN',
            message: error.message
          }
        });
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'INTERNAL_ERROR',
          message: '清理过期日志失败'
        }
      });
    }
  }

  /**
   * 记录错误日志
   */
  static async logError(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      if (!isAdmin(req)) {
        throw new AuthorizationError('需要管理员权限');
      }

      const { error, metadata } = req.body;
      
      if (!error || typeof error !== 'object') {
        res.status(400).json({
          success: false,
          error: {
            code: 'INVALID_INPUT',
            message: '无效的错误日志数据'
          }
        });
        return;
      }

      const errorLog = await ErrorLogService.logError(error, metadata);

      res.json({
        success: true,
        data: errorLog
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        error: {
          code: 'INTERNAL_ERROR',
          message: '记录错误日志失败'
        }
      });
    }
  }
}
